<!-- @format -->

<template>
  <view>
    <view
      @click="handleClick"
      :class="{
        'item-text': true,
        'file-text': !isDirectory,
        'directory-text': isDirectory,
        selected: isSelected,
      }"
    >
      <span v-show="expandText" class="expand-text">{{ expandText }}</span>
      <span>{{ name }}</span>
    </view>
    <view v-if="isDirectory && isExpand" class="sub-directory">
      <tree-item-loop
        v-for="(item, key) in item.children"
        :key="key"
        :item="item"
        :current-path="currentPath"
        @select="$emit('select', $event)"
      />
    </view>
  </view>
</template>

<script lang="ts" setup>
import { defineProps, defineEmits, ref, computed, effect } from 'vue'
import TreeItemLoop from './TreeItemLoop.vue'

const props = defineProps({
  item: {
    type: Object,
    required: true,
  },
  currentPath: {
    type: String,
  },
  expand: {
    type: Boolean,
    default: false,
  },
})

const emit = defineEmits(['select'])

const isDirectory = computed(() => props.item.direction)
const name = computed(() => {
  const result = props.item.name || props.item.path || ''
  return result.replace('.md', '')
})
const isExpand = ref(false)
const isSelected = computed(() => {
  if (isDirectory.value) {
    return false
  }
  const result = props.currentPath === props.item.path
  return result
})

const expandText = computed(() => {
  if (!isDirectory.value) return ''
  return isExpand.value ? '- ' : '+ '
})

const handleClick = () => {
  if (!isDirectory.value) {
    emit('select', props.item)
  }
  isExpand.value = !isExpand.value
}

effect(() => {
  isExpand.value = props.expand
})
</script>

<style scoped>
.item-text {
  display: flex;
  align-items: center;
  line-height: 180%;
}

.expand-text {
  line-height: 1;
  padding-bottom: 8rpx;
  margin-right: 8rpx;
}

.file-text {
  color: #555; /* 文件文本颜色 */
  cursor: pointer; /* 鼠标指针样式 */
}

.directory-text {
  color: #555; /* 目录文本颜色 */
  cursor: pointer; /* 鼠标指针样式 */
  font-size: 36rpx;
}

.selected {
  font-weight: bold;
}

.sub-directory {
  margin-left: 20px; /* 子目录缩进 */
  /* padding-left: 10px; 左内边距 */
  /* border-left: 1px solid #eaecef; 左边框 */
}
</style>
